<template>
  <div style="margin-top: 5px">
    <el-row :style="{height: conmpontHeight+'px'}" :gutter="10">
      <el-col :span="12">


        <el-form ref="user"
                 :model="userForm"
                 label-position="fight"
                 label-width="80px"
                 :rules="rules.user"
                 :inline=true
                 :hide-required-asterisk=true
                 :class="{animated:userShake,shake:userShake}">
          <el-form-item label="用户名"  prop="name">
            <el-input v-model="userForm.name">
              <el-button slot="append" type="info" :disabled="searchdisabled" @click="userSearch" icon="el-icon-search">查询
              </el-button>
            </el-input>

          </el-form-item>
        </el-form>

        <el-tree
          ref="userTree"
          :data="userTree"
          show-checkbox
          node-key="id"
          accordion
          highlight-current
          @check="userTreeSelect"
          check-strictly
          :filter-node-method="userTreeFilter"
         >
        </el-tree>
      </el-col>

      <el-col :span="12" style="overflow: hidden">

        <el-form ref="role"
                 :model="roleForm"
                 label-position="right"
                 label-width="80px"
                 :rules="rules.role"
                 :hide-required-asterisk=true
                 :inline="true">
          <el-form-item label="角色名" prop="name" :class="{animated:roleShake,shake:roleShake}"
          >

            <el-autocomplete
              v-model="roleForm.name"
              :fetch-suggestions="roleFilter"
              placeholder="请输入内容"
              @select="roleSelect"
            >
              <el-button slot="append" type="info" :disabled="searchdisabled" @click="roleSearch" icon="el-icon-search"
                         size="mini">查询
              </el-button>

            </el-autocomplete>
          </el-form-item>

          <el-form-item style="float: right">
            <el-button-group>
              <el-button type="primary" plain :disabled="searchdisabled" @click="updateRole" icon="el-icon-circle-plus"
                         size="small">保存
              </el-button>
              <el-button type="info" plain :disabled="searchdisabled" @click="rest" icon="el-icon-error"
                         size="small">取消
              </el-button>
            </el-button-group>

          </el-form-item>

        </el-form>

        <div :style="{height: (conmpontHeight-60)+'px'}">
          <el-scrollbar style="height: 100%;width: 100%;overflow-x: hidden">
            <el-tree
              ref="roleTree"
              :data="roleTree"
              show-checkbox
              node-key="id"
              accordion
              :filter-node-method="roleTreeFilter"
            >
            </el-tree>
          </el-scrollbar>

        </div>








      </el-col>
    </el-row>
  </div>

</template>

<script>
  import { getRolesLikeName } from '@/api/sysrole'
  import { GetUserDepartment ,GetRolesById} from '@/api/sysuser'
  import { GetRoleTree } from '@/api/sysrole'
  import { UpdateUserRole } from '@/api/sysUserRole'

  export default {
    mounted() {
      const parHeight = this.$parent.$parent.$el.offsetHeight
      this.conmpontHeight = parHeight - 60 - 34
      GetUserDepartment('').then(res => {
        this.userTree = res.data
      })

      GetRoleTree('').then(res => {
        this.roleTree = res.data
      })
    },
    data() {
      return {
        searchLoad: false,
        searchdisabled: false,
        conmpontHeight: 100,
        userShake: false,
        roleShake: false,
        selectUser:"",
        userForm: {
          name: ''
        },
        roleForm: {
          name: ''
        },
        roleOpt: [],
        rules: {
          role: {
            name: [
              { required: true, message: '请选择', trigger: 'change' }
            ]
          },
          user: {
            name: [
              { required: true, message: '请选择', trigger: 'blur' }
            ]
          }
        },
        userTree: [],
        roleTree: []
      }
    },
    methods: {
      roleSearch() {
        const that=this
        new Promise((resolve, reject) => {
          that.roleShake = false
          that.searchdisabled = true
          resolve()
        }).then(()=>{
          that.$refs.role.validate(valid => {
            if (valid) {
              that.$refs.roleTree.filter(this.userForm.name)
            } else {
              that.roleShake = true
              that.$refs.roleTree.filter('')
            }
          })
          that.searchdisabled = false
        })
      /*  const that=this
        that.roleShake = false
        that.searchdisabled = true
        that.$refs.role.validate(valid => {
          if (valid) {
            that.$refs.roleTree.filter(this.userForm.name)
          } else {
            that.roleShake = true
            that.$refs.roleTree.filter('')
          }
        })
        that.searchdisabled = false*/

      },
      roleFilter(roleName, cb) {
        getRolesLikeName(roleName).then(res => {
          this.roleOpt = res.data.map(obj => {
            return {
              label: obj.id,
              value: obj.name
            }
          })
          cb(this.roleOpt)
        })
      },
      roleSelect(item) {
        this.roleForm.name = item.value
        console.log(item)
      },
      userTreeSelect(data) {
        console.log("data.id",data.id)
        if (isNaN(data.id)){
          this.$alert('请选择用户', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.$refs.userTree.setCheckedNodes([])

            }
          })
        }else {
          //判断是否是取消选择

          if (this.selectUser==data.id){
            console.log("getCheckedKeys",this.$refs.userTree.getCheckedKeys()[0])
            this.$refs.userTree.setCheckedNodes([])
            this.$refs.roleTree.setCheckedNodes([])
            this.selectUser=""
          }else {
            this.$confirm('是否选择' + data.label, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$refs.userTree.setCheckedNodes([data])
              this.selectUser=this.$refs.userTree.getCheckedKeys()[0]
              // 加载roletree
              GetRolesById(data.id).then(res=>{
                console.log('角色',res.data)
                this.$refs.roleTree.setCheckedKeys([...res.data])
              })

            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
              this.$refs.userTree.setCheckedNodes([])
              this.selectUser=""
            })
          }

        }

      },
      userTreeFilter(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      userSearch() {
       /* const that=this
        new Promise((resolve, reject) => {
          that.userShake = false
          resolve()
        }).then(()=>{
          that.$refs.user.validate(valid => {
            if (valid) {
              that.$refs.userTree.filter(this.userForm.name)
            } else {
              that.userShake = true
              that.$refs.userTree.filter('')
            }
          })
        })*/
        const that=this
        new Promise(function (resolve, reject) {
          that.userShake = false
          that.searchdisabled = true
          //console.log("click")
          resolve()
        }).then(()=>{
          that.$refs.user.validate(valid => {
            if (valid) {
              that.$refs.userTree.filter(this.userForm.name)
              //console.log("没有走")
            } else {
              that.userShake = true
              //console.log("走了")
              that.$refs.userTree.filter('')
            }
          })
          that.searchdisabled = false
        })
      },
      roleTreeFilter(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      updateRole(){
        console.log('roleTree',this.$refs.roleTree.getCheckedKeys())
        console.log('userTree',  this.$refs.userTree.getCheckedKeys())
        UpdateUserRole(this.$refs.userTree.getCheckedKeys()[0],this.$refs.roleTree.getCheckedKeys()).then(res=>{
          this.$message({
            type: 'success',
            message: '保存成功'
          })
        })



      },
      rest(){
        this.$refs.roleTree.setCheckedKeys([])
        this.$refs.userTree.setCheckedKeys([])
        this.selectUser=""
      }
    }
  }
</script>

<style scoped>


</style>
